<template>
  <div>
    <el-row style=";background:#FFFFFF">
      <el-row style="padding:10px">
        <el-tabs v-model="mTabActive" @tab-click="tabClick">
          <el-tab-pane label="行程查询" name="first">
            <el-row>
              <el-col :span="4">
                <el-input style="width:90%" v-model="mSearchKey" placeholder="输入关键字"></el-input>
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  style="margin-left:10px;width:90%"
                  v-model="mDateRange"
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-col>
              <el-col :span="4">
                <!-- 状态选择 -->
                <el-select style="width:90%" v-model="mOrderStatus" placeholder="请选择状态">
                  <el-option
                    v-for="item in mLstOrderStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-search" circle type="primary" @click="searchByOrder()"></el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="司机行程记录" name="second">
            <el-row>
              <el-col :span="4">
                <el-select style="width:90%" v-model="mSelectDriver" filterable placeholder="请选择司机">
                  <el-option
                    v-for="item in mDrivers"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  style="margin-left:10px;width:90%"
                  v-model="mDateRange"
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-col>
              <el-col :span="4">
                <!-- 状态选择 -->
                <el-select style="width:90%" v-model="mOrderStatus" placeholder="请选择状态">
                  <el-option
                    v-for="item in mLstOrderStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-search" circle type="primary" @click="searchDriver()"></el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="车辆行程记录" name="third">
            <el-row>
              <el-col :span="4">
                <el-select style="width:90%" v-model="mSelectCar" filterable placeholder="请选择车辆">
                  <el-option
                    v-for="item in mCars"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  style="margin-left:10px;width:90%"
                  v-model="mDateRange"
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-col>
              <el-col :span="4">
                <!-- 状态选择 -->
                <el-select style="width:90%" v-model="mOrderStatus" placeholder="请选择状态">
                  <el-option
                    v-for="item in mLstOrderStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button icon="el-icon-search" circle type="primary" @click="searchCars()"></el-button>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 第三方车辆行程查询 -->
          <el-tab-pane label="第三方车辆记录" name="fourth">
            <el-row>
              <el-col :span="4">
                <!-- <el-input style="width:90%" v-model="mSearchKey" placeholder="输入关键字"></el-input> -->
                <el-select
                  style="width:90%"
                  v-model="mSelectThirdCompany"
                  filterable
                  placeholder="请选择三方调度公司"
                >
                  <el-option
                    v-for="item in mThridCompany"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  style="margin-left:10px;width:90%"
                  v-model="mDateRange"
                  type="daterange"
                  align="right"
                  value-format="yyyy-MM-dd"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-col>
              <el-col :span="4">
                <!-- 状态选择 -->
                <el-select style="width:90%" v-model="mOrderStatus" placeholder="请选择状态">
                  <el-option
                    v-for="item in mLstOrderStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button
                  icon="el-icon-search"
                  circle
                  type="primary"
                  @click="searchByThirdCompany()"
                ></el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>

      <el-table :data="mTableData" v-loading="mTableLoading" border stripe style="width: 100%">
        <el-table-column label="编号" prop="id"></el-table-column>
        <el-table-column label="用车科室" prop="applyPartmentName"></el-table-column>
        <el-table-column label="申请人" prop="applyUserName"></el-table-column>
        <el-table-column label="联系电话" prop="tel" width="120"></el-table-column>
        <el-table-column label="乘车人" prop="strPassenger1"></el-table-column>
        <el-table-column label="乘车地点" prop="setoffAddress" width="220"></el-table-column>
        <el-table-column label="到达地点" prop="arrivalAddress" width="220"></el-table-column>
        <el-table-column label="发车时间" prop="setoffTime"></el-table-column>
        <el-table-column label="返回时间" prop="backTime"></el-table-column>
        <el-table-column label="司机" v-if="mTabActive=='second'" prop="strDriver1"></el-table-column>
        <el-table-column label="车辆" v-if="mTabActive=='third'" prop="strCar1"></el-table-column>
        <el-table-column label="用车数量" prop="requstCarNum"></el-table-column>
        <el-table-column label="乘坐人数" prop="passengersNum"></el-table-column>
        <el-table-column label="用车要求" prop="note"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="状态" prop="strstatus"></el-table-column>
        <el-table-column label="三方公司" v-if="mTabActive=='fourth'" prop="thirdCompanyName"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="$refs.refOrderDetailDialog.showOrderDetailDialog(scope.row)"
            >
              <span class="FontBase">详情</span>
            </el-button>

            <el-button type="text" v-if="scope.row.showClose" @click="showCloseDialog(scope.row)">
              <span class="FontBase" style="color:#F56C6C">关闭</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top:10px;padding-bottom:10px">
        <el-pagination
          style="float:right"
          v-if="totalPage"
          background
          layout="prev, pager, next,jumper"
          @current-change="pageIndexChange()"
          :current-page.sync="page"
          :page-count="totalPage"
        ></el-pagination>
        <span
          v-if="totalPage"
          style="float:right;font-size:14px;margin-top:5px;color:#606266;margin-right:20px"
        >
          共&nbsp;
          <span style="color:#F56C6C">{{totalPage}}</span>&nbsp;页/&nbsp;
          <span style="color:#F56C6C">{{totalCount}}</span>&nbsp;条数据
        </span>
      </el-row>
    </el-row>

    <v-OrderDetailDialog ref="refOrderDetailDialog"></v-OrderDetailDialog>
    <el-dialog title="提示" :visible.sync="mCloseDialog" width="30%">
      <span>确认关闭行程</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mCloseDialog = false">取 消</el-button>
        <el-button type="primary" @click="closeOrder()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<style >
.mainDiv {
  min-width: 100%;
}
.topRow {
  min-width: 100%;
  background: white;
  padding: 10px;
  border-radius: 2px;
  color: #606266;
  font-size: 16px;
}
.spanPoint {
  cursor: pointer;
}
.borderMain {
  border-style: solid;
  border-color: #ebeef5;
  border-width: 1px;
}
.borderAround {
  padding: 10px;
  border-style: solid;
  border-color: #ebeef5;
  border-width: 1px;
}
.ctrlCard {
}
</style>



<script>
import { getRequestHeader, loginApi, getThirdCompanyApi } from "../api/user.js";
import { getCarsApi } from "../api/car.js";
import { getNowFormatDate, getWeekToday } from "../api/util.js";
import { turnOrderStatus } from "../api/orderHelper.js";
import {
  queryControllerOrdersApi,
  getDriversApi,
  dispatchOrderApi,
  dispatchThirdCompanyApi,
  closeOrderApi
} from "../api/order.js";
import { Loading } from "element-ui";
import OrderDetailDialog from "./widget/OrderDetailDialog.vue";
export default {
  data() {
    return {
      mTableData: [],
      page: 1,
      totalPage: 0,
      pagesize: 12,
      totalCount: 0,

      pageCar: 1,
      totalPageCar: 0,
      pagesizeCar: 2,

      pageDriver: 1,
      totalPageDriver: 0,
      pagesizeDriver: 2,

      mOrderStatus: "all",
      mTableLoading: false,
      mDispatchDialog: false,
      mSelectRow: {},
      mThirdDispatchDialog: false,
      mCdmMap: [],
      mDrivers: [],
      mCars: [],
      mThridCompany: [],
      mCloseDialog: false,
      mActiveTabName: "first",
      mTmpCtrls: [],
      mCarSelectDialog: false,
      mDriverSelectDialog: false,
      mSearchKey: undefined,
      mDateRange: undefined,
      mSelectDriver: undefined,
      mFilter: undefined,
      mSelectCar: undefined,
      mTabActive: "first",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      mLstOrderStatus: [
        { label: "全部状态", value: "all" },
        { label: "待审核", value: "created" },
        { label: "待调度", value: "allowed" },
        { label: "待出发", value: "dispatched" },
        { label: "已出发", value: "travelStarted" },
        { label: "待确认", value: "travelEnded" },
        { label: "已完成", value: "finished" },
        { label: "已取消", value: "cancled" },
        { label: "未通过", value: "refused" },
        { label: "已关闭", value: "closed" }
      ],
      mSelectThirdCompany: undefined
    };
  },
  components: {
    "v-OrderDetailDialog": OrderDetailDialog
  },
  created() {},
  mounted() {
    this.getDrivers();
    this.getCars();
    this.getThridCompany();
    this.queryControllerOrders();
  },
  watch: {
    mOrderStatus(v1, v2) {
      this.searchAll();
    }
  },
  methods: {
    showFullLoading() {
      this.mFullLoading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    clsoeFullLoading() {
      if (this.mFullLoading) {
        this.mFullLoading.close();
      }
    },
    setPagesize(size) {
      this.page = 1;
      this.pagesize = size;
      this.queryControllerOrders();
    },
    pageIndexChange() {
      // this.page = this.mUiPageIndex - 1;
      this.queryControllerOrders();
    },
    calDate() {
      var d = {};
      d.start = undefined;
      d.end = getNowFormatDate() + " 23:59:59";
      if (this.mDateRange) {
        var arrs = ("" + this.mDateRange).split(",");
        if (arrs && arrs.length == 2) {
          d.start = arrs[0];
          d.end = arrs[1] + " 23:59:59";
        }
      }
      return d;
    },
    queryControllerOrders() {
      var that = this;
      that.showFullLoading();
      that.mTableLoading = true;
      var dateR = this.calDate();

      queryControllerOrdersApi(
        this.page,
        this.pagesize,
        [this.mOrderStatus],
        dateR.start,
        dateR.end,
        this.mFilter,
        getRequestHeader(),
        new (function() {
          this.success = function(data) {
            that.clsoeFullLoading();
            that.mTableLoading = false;
            that.page = data.currentPage;
            that.totalCount = data.totalCount;
            that.totalPage = data.totalPage;
            data.list.forEach(element => {
              element.strDriver1 = "-";
              if (element.lstDrivers && element.lstDrivers.length > 0) {
                element.strDriver1 = element.lstDrivers[0].name;
              }
              element.strCar1 = "-";
              if (element.lstCars && element.lstCars.length > 0) {
                element.strCar1 = element.lstCars[0].name;
              }

              if (element.passengers && element.passengers.length > 0) {
                element.strPassenger1 = element.passengers[0].name;
              } else {
                element.strPassenger1 = "-";
              }

              // console.log("========" + element.status);
              if (
                element.status == "dispatched" ||
                element.status == "allowed"
              ) {
                element.showClose = true;
              } else {
                element.showClose = false;
              }

              element.strstatus = turnOrderStatus(element.status);
            });

            that.mTableData = data.list;
          };
          this.fail = function(msg) {
            that.clsoeFullLoading();
            that.mTableLoading = false;
            that.mTableData = [];
          };
        })()
      );
    },
    selectRow(order) {
      this.mSelectRow = order;
      this.mDispatchDialog = true;
      this.mCdmMap = [];
      var item = {};
      item.index = 0;
      this.mCdmMap.push(item);
      this.getDrivers();
      this.getCars();
    },
    addLine() {
      var item = {};
      item.index = this.mCdmMap.length;
      this.mCdmMap.push(item);
    },
    getThridCompany() {
      var that = this;
      getThirdCompanyApi(
        getRequestHeader(),
        new (function() {
          this.success = function(data) {
            that.mThridCompany = data;
          };
          this.fail = function(msg) {};
        })()
      );
    },
    getDrivers() {
      var that = this;
      getDriversApi(
        1,
        1000 * 1000,
        undefined,
        getRequestHeader(),
        new (function() {
          this.success = function(data) {
            that.mDrivers = that.refreshDrivers(data.list);
          };
          this.fail = function(msg) {};
        })()
      );
    },
    getCars() {
      var that = this;
      getCarsApi(
        1,
        1000 * 1000,
        undefined,
        getRequestHeader(),
        new (function() {
          this.success = function(data) {
            that.mCars = that.refreshCars(data.list);
          };
          this.fail = function(msg) {};
        })()
      );
    },
    refreshCars(lst) {
      var that = this;
      var result = [];
      lst.forEach(element => {
        var obj = {};
        obj.label = element.name + "（" + element.chepai + "）";
        obj.value = element.carId;
        result.push(obj);
      });
      return result;
    },
    refreshDrivers(lst) {
      var that = this;
      var result = [];
      lst.forEach(element => {
        var obj = {};
        obj.label = element.name;
        obj.value = element.userId;
        result.push(obj);
      });
      return result;
    },
    deleteDispatchRow(row) {
      // this.mCdmMap.$remove(row);
      this.mCdmMap.splice(this.mCdmMap.indexOf(row), 1);
    },
    dispatchOrder() {
      var that = this;
      console.log(JSON.stringify(this.mTmpCtrls, null, 2));

      // 计算得到对应关系
      var mapArray = [];
      this.mTmpCtrls.forEach(element => {
        if (element.driver && element.car && element.opType == "show") {
          var userId = element.driver.userId;
          var carId = element.car.carId;
          var rl = {};
          rl.userId = userId;
          rl.carId = carId;
          mapArray.push(rl);
        }
      });
      if (mapArray.length == 0) {
        that.$message.error("请确认分配关系");
        return;
      }

      // 判断出是否有分配重复的
      {
        var hash = {};
        for (var i in this.mapArray) {
          if (hash[this.mapArray[i].userId]) {
            that.$message.error("司机分配重复，请检查");
            return;
          }
          hash[this.mapArray[i].userId] = true;
        }
      }

      {
        var hash = {};
        for (var i in this.mapArray) {
          if (hash[this.mapArray[i].carId]) {
            that.$message.error("车辆分配重复，请检查");
            return;
          }
          hash[this.mapArray[i].carId] = true;
        }
      }

      that.showFullLoading();
      dispatchOrderApi(
        this.mSelectRow.id,
        mapArray,
        getRequestHeader(),
        new (function() {
          this.fail = function(msg) {
            that.clsoeFullLoading();
            that.$message.error(msg);
          };
          this.success = function(data) {
            that.clsoeFullLoading();
            that.mDispatchDialog = false;
            that.$message.success("分配成功");
            that.queryControllerOrders();
          };
        })()
      );
    },

    closeOrder() {
      var that = this;
      this.showFullLoading();
      closeOrderApi(
        this.mSelectRow.id,
        getRequestHeader(),
        new (function() {
          this.fail = function(msg) {
            that.clsoeFullLoading();
            that.$message.error(msg);
          };
          this.success = function(data) {
            that.clsoeFullLoading();
            that.mCloseDialog = false;
            that.$message.success("关闭成功");
            that.queryControllerOrders();
          };
        })()
      );
    },
    thirdDispatch(order) {},
    dispatchThirdCompany() {
      var that = this;
      if (!this.mSelectRow.thirdCompanyId) {
        this.$message.error("请选择三方公司");
        return;
      }
      that.showFullLoading();
      dispatchThirdCompanyApi(
        this.mSelectRow.id,
        this.mSelectRow.thirdCompanyId,
        getRequestHeader(),
        new (function() {
          this.fail = function(msg) {
            that.clsoeFullLoading();
            that.$message.error(msg);
          };
          this.success = function(data) {
            that.clsoeFullLoading();
            that.mDispatchDialog = false;
            that.$message.success("分配成功");
            that.queryControllerOrders();
          };
        })()
      );
    },
    handleTabClick() {},
    showCtrlDialog(row) {
      // this.selectRow(row);
      this.mSelectRow = row;
      this.mDispatchDialog = true;
      // 初始化表格
      var o = {};
      o.opType = "add";
      this.mTmpCtrls = [];
      this.mTmpCtrls.push(o);
    },
    showCarSelelctDialog() {
      this.mCarSelectDialog = true;
      this.pageCar = 1;
      this.getCars();
    },
    showDriverSelelctDialog() {
      this.mDriverSelectDialog = true;
      this.pageDriver = 1;
      this.getDrivers();
    },
    pageCarIndexChange() {
      this.getCars();
    },
    pageDriverIndexChange() {
      this.getDrivers();
    },
    selectCar(row) {
      var o = this.mTmpCtrls[this.mTmpCtrls.length - 1];
      o.car = row;
      this.$set(this.mTmpCtrls, this.mTmpCtrls.length - 1, o);
      this.mCarSelectDialog = false;
    },
    selectDriver(row) {
      var o = this.mTmpCtrls[this.mTmpCtrls.length - 1];
      o.driver = row;
      this.$set(this.mTmpCtrls, this.mTmpCtrls.length - 1, o);
      this.mDriverSelectDialog = false;
    },
    confirmAddLine() {
      var o = this.mTmpCtrls[this.mTmpCtrls.length - 1];
      o.opType = "show";
      var o1 = {};
      o1.opType = "add";
      this.mTmpCtrls.push(o1);
    },
    delfirmLine(index) {
      this.mTmpCtrls.splice(index, 1);
    },
    tabClick(tab, event) {
      // console.log(tab.name, event);
      this.mSelectCar = undefined;
      this.mSearchKey = undefined;
      this.mSelectDriver = undefined;
      this.mSelectThirdCompany = undefined;
      this.mDateRange = undefined;
      this.mOrderStatus = "all";
      if (tab.name != "first") {
        this.mTableData = [];
        this.searchByOrder();
        if ((tab.name = "second")) {
        } else if ((tab.name = "third")) {
        }
      } else {
        this.mFilter = {};
        this.page = 1;
        this.searchByOrder();
      }
    },
    searchByOrder() {
      this.page = 1;
      console.log(this.mSearchKey + " " + this.mDateRange);
      this.mFilter = {};
      this.mFilter.key = this.mSearchKey;
      this.queryControllerOrders();
    },
    searchByThirdCompany() {
      this.page = 1;
      this.mFilter = {};
      this.mFilter.thirdCompanyId = this.mSelectThirdCompany;
      console.log(this.mFilter,undefined,2)
      this.queryControllerOrders();
    },

    searchDriver() {
      this.page = 1;
      this.mFilter = {};
      this.mFilter.searchDriverId = this.mSelectDriver;
      // if (!this.mFilter.searchDriverId) {
      //   this.$message.error("请选择司机");
      //   return;
      // }
      console.log(
        this.mSearchKey + " " + this.mDateRange + " " + this.mSelectDriver
      );
      this.queryControllerOrders();
    },
    searchCars() {
      this.page = 1;
      this.mFilter = {};
      this.mFilter.searchCarId = this.mSelectCar;
      // if (!this.mFilter.searchCarId) {
      //   this.$message.error("请选择车辆");
      //   return;
      // }
      console.log(
        this.mSearchKey + " " + this.mDateRange + " " + this.mSelectCar
      );
      this.queryControllerOrders();
    },
    searchAll() {
      this.page = 1;
      this.mFilter = {};
      this.mFilter.searchCarId = this.mSelectCar;
      this.mFilter.searchDriverId = this.mSelectDriver;
      this.mFilter.thirdCompanyId = this.mSelectThirdCompany;
      this.queryControllerOrders();
    },
    showCloseDialog(row) {
      this.mSelectRow = row;
      this.mCloseDialog = true;
    }

    //----------over methods------
  }
};
</script>